package com.kuang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kuang.pojo.User;
import com.kuang.mapper.UserMapper;
import com.kuang.pojo.UserRole;
import com.kuang.service.UserRoleService;
import com.kuang.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuang.utils.KuangUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService,UserDetailsService {
    @Autowired
    UserService userService;
    @Autowired
    UserRoleService roleService;
    @Autowired
    HttpSession session;


    /**
     * 通过用户名加载用户详细信息。
     * 
     * @param s 用户名
     * @return UserDetails 包含用户详细信息的对象
     * @throws UsernameNotFoundException 如果找不到用户则抛出此异常
     */
    @Override
    public UserDetails loadUserByUsername(String s) {
        // 通过用户名查询用户
        User user = userService.getOne(new QueryWrapper<User>().eq("username", s));
        // 放入session
        session.setAttribute("loginUser",user);
    
        //创建一个新的UserDetails对象，最后验证登陆的需要
        UserDetails userDetails=null;
        if(user!=null){
            //System.out.println("未加密："+user.getPassword());
            //String BCryptPassword = new BCryptPasswordEncoder().encode(user.getPassword());
            // 登录后会将登录密码进行加密，然后比对数据库中的密码，数据库密码需要加密存储！
            String password = user.getPassword();
    
            //创建一个集合来存放权限
            Collection<GrantedAuthority> authorities = getAuthorities(user);
            //实例化UserDetails对象
            userDetails=new org.springframework.security.core.userdetails.User(s,password,
                            true,
                            true,
                            true,
                            true, authorities);
        }
        return userDetails;
    }


    private Collection<GrantedAuthority> getAuthorities(User user){
        List<GrantedAuthority> authList = new ArrayList<>();
        UserRole userRole = roleService.getById(user.getRoleId());
        if(userRole!=null){
            String roleName = userRole.getName();
            authList.add(new SimpleGrantedAuthority("ROLE_"+roleName));
        }
        return authList;


    }

}
